// import { TypeInjectFocus } from "@/focus/type";
// import FocusPopup from "./popup";
// import { getUUid } from "@/focus/path/until";

import { getUUid } from "@/focus/path/until";
import { focusStore } from "@/focus/store";
import Popup from "./popup"
import { TypePopupItem } from "@/focus/type";
import { DefineComponent, VNode, defineComponent, ref } from "vue";
import Switch from "../switch";

export function usePopup(params?: { pUid?: string }) {
  const focusInject = focusStore.inject()
  const popupKeyBoardLook = ref(true)
  const DomInfo = ref<DefineComponent>()
  const uid = params?.pUid || getUUid()
  let popupItem: TypePopupItem = getPopupItem({ pUid: uid })
  function onHide() {
    popupItem.visible = false
    DomInfo.value = undefined
    setPopup()
  }
  function onOpen(dom: VNode, params?: { pUid?: string }) {
    if (typeof params?.pUid === "string" && params.pUid !== uid) {
      popupItem = getPopupItem({ pUid: params.pUid })
    }
    popupItem.visible = true
    DomInfo.value = defineComponent({
      render() {
        return dom
      }
    })
    setPopup()
  }

  function getPopupItem(params: { pUid: string }): TypePopupItem {
    return {
      uid: params.pUid,
      visible: false,
      zIndex: 0,
      Popupele: defineComponent({
        render() {
          return <Popup uid={params.pUid}>
            <Switch onBack={onHide} popupKeyBoardLook={popupKeyBoardLook.value}>
              {DomInfo.value ? <DomInfo.value></DomInfo.value> : null}
            </Switch>
          </Popup>
        }
      })
    }
  }

  function setPopup() {
    let popIdx = -1
    focusInject.state.popupList.value.forEach((v, idx) => {
      if (v.zIndex > popupItem.zIndex) {
        popupItem.zIndex = v.zIndex + 1
      }
      if (v.uid === uid) {
        popIdx = idx
      }
    })
    popupKeyBoardLook.value = !popupItem.visible
    if (popIdx >= 0) {
      focusInject.state.popupList.value[popIdx] = popupItem
    } else {
      focusInject.state.popupList.value.push(popupItem)
    }
  }

  return {
    onOpen,
    onHide,
  }
}